package com.example.park

import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
import android.widget.ArrayAdapter
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.example.base.entity.DictEntityItem
import com.example.base.entity.ParkEntityItem
import com.example.base.mvi.BaseActivity
import com.example.base.mvi.HttpType
import com.example.base.mvi.UiState
import com.example.park.databinding.ActivityParkEditBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import okhttp3.internal.wait

@Route(path = "/park/ParkEditActivity")
@AndroidEntryPoint
class ParkEditActivity : BaseActivity<ActivityParkEditBinding,ParkIntent,ParkViewModel>() {
    //定义一个集合  用来接收type 用来接收area
    lateinit var types:Collection<DictEntityItem>
    lateinit var areas:Collection<DictEntityItem>

    var spaceType = "标准车位"//定义变量，显示车位类型
    var  areaId = -1
    var areaName = ""
    var status = "空闲"
    @Autowired
    @JvmField
    var pid = -1
    override fun getLayout(): Int  = R.layout.activity_park_edit

    override fun getVM(): Class<ParkViewModel>  = ParkViewModel::class.java

    override fun initView() {
        ARouter.getInstance().inject(this)
        //因为有字典的请求展示  所以我们在字典请求成功后请求详情


        binding.head.apply {
            headBack.setOnClickListener {
                finish()
            }
            headTitle.text = "车位编辑"
            headAdd.isVisible = false
        }
        //发送请求字典
        viewModel.sendIntent(ParkIntent.dict)
        //给rg添加点击事件
        binding.rgStatus.setOnCheckedChangeListener { group, checkedId ->
            when(checkedId){
                R.id.rb1->{
                    status = "空闲"
                    binding.ll.isVisible = false
                    binding.etUsername.setText("")
                    binding.etCarNo.setText("")
                }
                R.id.rb2->{
                    status = "占用"
                    binding.ll.isVisible = true
                }
                R.id.rb3->{
                    status = "维修中"
                    binding.ll.isVisible = false
                    binding.etUsername.setText("")
                    binding.etCarNo.setText("")
                }
            }
        }
        //点击保存，调用接口
        binding.btnSave.setOnClickListener {
            val item = ParkEntityItem(areaId,areaName,0,binding.etCarNo.text.toString(),
                binding.etRemark.text.toString(),binding.etSpaceNumber.text.toString(),
                status,spaceType,0,binding.etUsername.text.toString())
            //新增和修改的区别   一个知道id 一个不知道id
            if(pid!=-1){
                item.id = pid
                viewModel.sendIntent(ParkIntent.parkUpdate(pid,item))
            }else{
                viewModel.sendIntent(ParkIntent.parkAdd(item))
            }

        }
    }

    override fun initData() {
        lifecycleScope.launch {
            viewModel.uiState.collect{
                when(it){

                    is UiState.onSuccess<*> -> {
                        when(it.type){
                            HttpType.DEFAULT -> {
                                if(pid!=-1){
                                    //需要请求详情
                                    viewModel.sendIntent(ParkIntent.parkDetail(pid))
                                }
                                val items = it.data as Collection<DictEntityItem>
                                types = items.filter { it.key == "park" }
                                //显示到spinner
                                val typeAdapter = ArrayAdapter(this@ParkEditActivity,
                                    androidx.appcompat.R.layout.support_simple_spinner_dropdown_item,
                                   types.map { it.value }
                                )
                                typeAdapter.setDropDownViewResource(androidx.appcompat.R.layout.support_simple_spinner_dropdown_item)
                                binding.etSpaceType.adapter = typeAdapter
                                binding.etSpaceType.onItemSelectedListener = object :OnItemSelectedListener{
                                    override fun onItemSelected(
                                        parent: AdapterView<*>?,
                                        view: View?,
                                        position: Int,
                                        id: Long
                                    ) {
                                        spaceType = types.toList()[position].value
                                    }

                                    override fun onNothingSelected(parent: AdapterView<*>?) {

                                    }
                                }
                                //显示区域
                                areas = items.filter { it.key=="parkArea" }
                                val areaAdapter = ArrayAdapter(this@ParkEditActivity,
                                    androidx.appcompat.R.layout.support_simple_spinner_dropdown_item,
                                    areas.map { it.value })
                                areaAdapter.setDropDownViewResource(androidx.appcompat.R.layout.support_simple_spinner_dropdown_item)
                                binding.etAreaName.adapter = areaAdapter
                                binding.etAreaName.onItemSelectedListener = object :OnItemSelectedListener{
                                    override fun onItemSelected(
                                        parent: AdapterView<*>?,
                                        view: View?,
                                        position: Int,
                                        id: Long
                                    ) {
                                        val item = areas.toList()[position]
                                        areaId = item.id
                                        areaName = item.value
                                    }

                                    override fun onNothingSelected(parent: AdapterView<*>?) {

                                    }
                                }

                            }
                            HttpType.ADD->{
                                ToastUtils.showLong("新增成功")
                                finish()
                            }
                            HttpType.DETAIL->{
                                //请求详情展示结果
                                val item = it.data as ParkEntityItem
                                binding.etSpaceNumber.setText(item.spaceNumber)

                                binding.etRemark.setText(item.remarks)
                                //下拉框回显
                                binding.etAreaName.setSelection(areas.map { it.value }.indexOf(item.areaName))
                                binding.etSpaceType.setSelection(types.map { it.value }.indexOf(item.spaceType))
                                //选中状态
                                when(item.spaceStatus){
                                    "空闲"->{
                                        binding.rgStatus.check(R.id.rb1)
                                        binding.ll.isVisible = false
                                    }
                                    "占用"->{
                                        binding.rgStatus.check(R.id.rb2)
                                        binding.ll.isVisible = true
                                        binding.etUsername.setText(item.userName)
                                        binding.etCarNo.setText(item.licensePlate)
                                    }
                                    else->{
                                        binding.rgStatus.check(R.id.rb3)
                                        binding.ll.isVisible = false
                                    }
                                }
                            }
                            HttpType.UPDATE->{
                                ToastUtils.showLong("修改成功")
                                finish()
                            }
                            else->{}
                        }
                    }
                    else->{}
                }
            }
        }
    }

}